<template>
  <div>
    <div class="header-text">账号设置</div>
    <div class="main-content">
      <div class="main-content-item">
        <span>密码</span>
        <el-text
          style="cursor: pointer"
          type="primary"
          size="large"
          @click="pwdDialogVisible = true"
        >
          重置
        </el-text>
      </div>
      <div class="main-content-item">
        <span>邮箱绑定</span>
        <div v-if="userStore.userInfo.email">
          <el-text style="margin-right: 16px" type="primary" size="large">
            {{ userStore.userInfo.email }}
          </el-text>
          <el-text
            style="cursor: pointer"
            type="primary"
            size="large"
            @click="emailDialogVisible = true"
          >
            修改邮箱
          </el-text>
        </div>
        <el-text
          style="cursor: pointer"
          type="primary"
          size="large"
          v-else
          @click="emailDialogVisible = true"
        >
          绑定
        </el-text>
      </div>
      <div class="main-content-item">
        <span>账号注销</span>
        <el-popconfirm title="是否注销当前账号？" @confirm="deleteUser">
          <template #reference>
            <el-text
              style="cursor: pointer"
              type="primary"
              size="large"
              @click=""
            >
              注销
            </el-text>
          </template>
        </el-popconfirm>
      </div>
      <el-dialog
        v-model="pwdDialogVisible"
        title="修改密码"
        width="500"
        align-center
      >
        <el-form
          ref="pwdForm"
          :model="pwdFormData"
          :rules="pwdRules"
          @keyup.enter="submitPwdForm"
          style="margin: 24px auto; width: 420px"
        >
          <el-form-item prop="password">
            <el-input
              v-model="pwdFormData.password"
              show-password
              size="large"
              type="password"
              placeholder="请输入旧密码"
              prefix-icon="Lock"
            />
          </el-form-item>
          <el-form-item prop="newPassword">
            <el-input
              v-model="pwdFormData.newPassword"
              show-password
              size="large"
              type="password"
              placeholder="请输入新密码"
              prefix-icon="Lock"
            />
          </el-form-item>
          <el-form-item prop="resetPassword">
            <el-input
              v-model="pwdFormData.resetPassword"
              show-password
              size="large"
              type="password"
              placeholder="请重新输入密码"
              prefix-icon="Lock"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              :loading="loading"
              size="large"
              style="width: 100%"
              @click="submitPwdForm"
            >
              修改并保存
            </el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <el-dialog
        v-model="emailDialogVisible"
        :title="userStore.userInfo.email ? '修改邮箱' : '绑定邮箱'"
        width="500"
        align-center
      >
        <el-steps
          style="max-width: 600px; margin-bottom: 24px"
          :space="200"
          :active="active"
          simple
          v-if="userStore.userInfo.email"
        >
          <el-step title="旧邮箱验证" :icon="Message" />
          <el-step title="绑定新邮箱" :icon="Edit" />
        </el-steps>
        <el-form
          ref="emailForm"
          :model="emailFormData"
          :rules="emailRules"
          @keyup.enter="submitEmailForm"
          style="margin: 0 auto; width: 420px"
        >
          <el-form-item prop="email">
            <el-input
              type="email"
              v-model="emailFormData.email"
              size="large"
              placeholder="请输入邮箱"
              prefix-icon="User"
            />
          </el-form-item>
          <el-form-item prop="captcha">
            <el-input
              v-model="emailFormData.captcha"
              size="large"
              placeholder="请输入验证码"
              prefix-icon="CircleCheck"
            >
              <template #append>
                <el-button :disabled="countdown > 0" @click="getEmailCaptcha()">
                  {{
                    countdown > 0 ? `${countdown}秒后重新获取` : '获取验证码'
                  }}
                </el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              :loading="loading"
              size="large"
              style="width: 100%"
              @click="submitEmailForm"
            >
              {{ active === 0 ? '下一步' : '修改并保存' }}
            </el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  reqGetBindingEmailCaptcha,
  reqGetNewEmailCaptcha,
  reqGetOldEmailCaptcha,
} from '@/api/email'
import { reqDeleteUser } from '@/api/user'
import useUserStore from '@/store/modules/user'
import { ElMessage } from 'element-plus'
import { reactive, ref } from 'vue'
import { Edit, Message } from '@element-plus/icons-vue'
import {
  reqBindingEmail,
  reqChangePwd,
  reqVerifyNewEmail,
  reqVerifyOldEmail,
} from '@/api/auth'

const userStore = useUserStore()
const emailDialogVisible = ref(false)
const pwdDialogVisible = ref(false)
const countdown = ref(0)
const active = ref(0)
const loading = ref(false)

let pwdForm = ref()
let pwdFormData = reactive({
  password: '',
  newPassword: '',
  resetPassword: '',
})

const checkPassword = (rule: any, value: any, callback: any) => {
  if (value.length < 6 || value.length > 16) {
    return callback(new Error('请输入6位到16位的密码'))
  } else {
    callback()
  }
}

const checkResetPassword = (rule: any, value: any, callback: any) => {
  if (value !== pwdFormData.newPassword) {
    return callback(new Error('密码不一致'))
  } else {
    callback()
  }
}

const pwdRules = reactive({
  password: [{ validator: checkPassword, trigger: 'blur' }],
  newPassword: [{ validator: checkPassword, trigger: 'blur' }],
  resetPassword: [
    { validator: checkPassword, trigger: 'blur' },
    {
      validator: checkResetPassword,
      trigger: 'blur',
    },
  ],
})

let emailForm = ref()
let emailFormData = ref({
  email: '',
  captcha: '',
})
const oldEmail = ref('')

const emailRules: any = reactive({
  email: [
    {
      required: true,
      type: 'email',
      message: '输入正确的邮箱',
      trigger: 'blur',
    },
  ],
  captcha: [
    { required: true, message: '输入验证码', trigger: 'blur' },
    { min: 6, max: 6, message: '必须为六位验证码', trigger: 'blur' },
  ],
})

const submitPwdForm = async () => {
  await pwdForm.value.validate()
  try {
    const { message } = await reqChangePwd(pwdFormData)
    ElMessage.success(message)
    pwdDialogVisible.value = false
  } catch (error) {
    ElMessage.error((error as Error).message)
  }
}

const getEmailCaptcha = async () => {
  await emailForm.value.validateField('email')
  try {
    if (userStore.userInfo.email) {
      if (active.value == 0) {
        const { message } = await reqGetOldEmailCaptcha(
          emailFormData.value.email,
        )
        ElMessage.success(message)
      } else {
        const { message } = await reqGetNewEmailCaptcha(
          emailFormData.value.email,
        )
        ElMessage.success(message)
      }
    } else {
      const { message } = await reqGetBindingEmailCaptcha(
        emailFormData.value.email,
      )
      ElMessage.success(message)
    }
    startTimer()
  } catch (error) {
    ElMessage({
      type: 'error',
      message: (error as Error).message,
    })
  }
}

const submitEmailForm = async () => {
  await emailForm.value.validate()
  if (userStore.userInfo.email) {
    if (active.value == 0) {
      submitOldEmailForm()
    } else {
      submitNewEmailForm()
    }
  } else {
    submitBindingEmailForm()
  }
}

const submitOldEmailForm = async () => {
  try {
    const { message } = await reqVerifyOldEmail(emailFormData.value)
    ElMessage.success(message)
    oldEmail.value = emailFormData.value.email
    emailFormData.value = {
      email: '',
      captcha: '',
    }
    active.value++
    countdown.value = 0
  } catch (error) {
    ElMessage.error((error as Error).message)
  }
}

const submitNewEmailForm = async () => {
  try {
    const { message } = await reqVerifyNewEmail({
      ...emailFormData.value,
      oldEmail: oldEmail.value,
    })
    ElMessage.success(message)
    await userStore.getUserInfo()
    emailDialogVisible.value = false
    emailFormData.value = {
      email: '',
      captcha: '',
    }
    active.value = 0
    countdown.value = 0
  } catch (error) {
    ElMessage.error((error as Error).message)
  }
}

const submitBindingEmailForm = async () => {
  try {
    const { message } = await reqBindingEmail(emailFormData.value)
    ElMessage.success(message)
    await userStore.getUserInfo()
    emailDialogVisible.value = false
    emailFormData.value = {
      email: '',
      captcha: '',
    }
    countdown.value = 0
  } catch (error) {
    ElMessage.error((error as Error).message)
  }
}

const startTimer = () => {
  countdown.value = 60
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value === 0) {
      clearInterval(timer)
    }
  }, 1000)
}

const deleteUser = async () => {
  try {
    const { message } = await reqDeleteUser()
    ElMessage.success(message)
    userStore.userLogout()
  } catch (error) {
    ElMessage.error((error as Error).message)
  }
}
</script>

<style scoped lang="scss">
.header-text {
  font-size: 18px;
  padding: 18px 22px;
  border-bottom: solid 1px var(--el-menu-border-color);
}

.main-content {
  padding: 8px 22px;

  .main-content-item {
    display: flex;
    height: 68px;
    align-items: center;
    font-size: 17px;
    justify-content: space-between;
    border-bottom: solid 1px var(--el-menu-border-color);
  }
}
</style>
